package hw03;

import java.util.Scanner;
import java.util.SortedSet;
import java.util.TreeSet;

public class Attribute implements Comparable<Attribute> {

	private String relation;
	private String name;
	
	public Attribute(String relation, String name) {
		this.relation = relation;
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public String getRelation() {
		return relation;
	}

	public void setRelation(String relation) {
		this.relation = relation;
	}
	
	@Override
	public String toString() {
		String toString = "";
		if(getRelation() != null) {
			toString += getRelation() + ".";
		}
		toString += getName();
		return toString;
	}

	@Override
	public int compareTo(Attribute o) {
		return getName().compareTo(o.getName());
	}
	
	@Override
	public boolean equals(Object obj) {
		if(obj instanceof Attribute) {
			Attribute o = (Attribute) obj;
			return getName().equals(o.getName());
		}
		return super.equals(obj);
	}
	
	public static Attribute parse(String statement, Schema schema) {
		String relation;
		String name;
		if(statement.contains(".")) {
			String[] components = statement.split("\\.");
			relation = components[0].trim();
			name = components[1].trim();
			for(RelationalSignature R : schema.getRelationalSignatures()) {
				if(R.getName().equals(relation)) {
					for(Attribute A : R.getAttributes()) {
						if(A.getName().equals(name)) {
							return A;
						}
					}
				}
			}
		} else {
			name = statement.trim();
			relation = null;
			for(RelationalSignature R : schema.getRelationalSignatures()) {
				for(Attribute A : R.getAttributes()) {
					if(A.getName().equals(name)) {
						return A;
					}
				}
			}
		}
		return new Attribute(relation, name);
	}
	
	public static SortedSet<Attribute> parseSet(String statement, Schema schema) {
		TreeSet<Attribute> attributes = new TreeSet<Attribute>();
		Scanner attributeScan = new Scanner(statement);
		attributeScan.useDelimiter(",");
		while(attributeScan.hasNext()) {
			attributes.add(Attribute.parse(attributeScan.next(), schema));
		}		
		return attributes;
	}

	public Attribute copy() {
		return new Attribute(getRelation()+"", getName()+"");
	}
	
}